package org.apache.database.enums;

import org.apache.database.dao.Condition;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;

public enum UpdataActionEnum {
    BASE();
    private StringBuffer sql;

    UpdataActionEnum() {

    }

    public UpdataActionEnum init(){
        this.sql =new StringBuffer();
        this.sql.append("UPDATE ");
        return this;
    }
    public UpdataActionEnum withTableName(String tableName){
        this.sql.append(" "+tableName+" SET");
        return this;
    }

    public String updateById(String id,Serializable idValue, Map<Serializable,Serializable> value){
        appendUpdateFieldAndValue(value);
        this.sql.append(" WHERE ");
        this.sql.append(" "+id+" ");
        this.sql.append(" = ");
        this.sql.append(idValue);
        return this.sql.toString();

    }

    public String update(Condition condition, Map<Serializable, Serializable> valueMap){
        appendUpdateFieldAndValue(valueMap);

        this.sql.append(condition.getSql());

        return this.sql.toString();
    }
    public String update(Condition condition){
        this.sql.append(condition.getSql());
        return this.sql.toString();
    }
    private void appendUpdateFieldAndValue(Map<Serializable, Serializable> valueMap){
        Iterator<Serializable> iterator = valueMap.keySet().iterator();
        while (iterator.hasNext()){
            String field = (String) iterator.next();
            this.sql.append("  "+field+" ");
            this.sql.append(" = ");
            Serializable serializable = valueMap.get(field);
            if (serializable instanceof String){
                this.sql.append("'"+serializable+"',");
            }else {
                this.sql.append(""+serializable+",");
            }
        }
        this.sql.deleteCharAt(this.sql.length()-1);
    }
}
